package com.chixing.interceptor;

import com.chixing.entity.VO.LoginUser;
import com.chixing.service.IUsersService;
import com.chixing.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoggingInterceptor implements HandlerInterceptor {

    @Autowired
    private IUsersService usersService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{
        //预检请求放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())){
            System.out.println("----------放行1111111111------------------");
            return true;
        }
        System.out.println("----执行拦截器JwtAuthInterceptor -------------");
        //拿到请求头的token
        String authHeader = request.getHeader("Authorization");
        System.out.println(authHeader);
        if (authHeader!=null && authHeader.startsWith("Bearer ")){
            String token = authHeader.substring(7);//去掉请求头的"Bearer "
            System.out.println("--------token =" + token);
            Result validateResult = usersService.validateAndRefreshToken(token);//刷新token
            //无效的token
            if (validateResult.getCode() != 200){
                //给出相应数据
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"error\":\"Unauthorized\"}");
                System.out.println("------拦截222222222222222---------");
                return false;
            }
            // 有效的 token
            Result loginUserResult = usersService.getLoginUserInfoById(token);
            LoginUser loginUser = (LoginUser) loginUserResult.getData();
            System.out.println("从token中解析的登录用户的信息是：--------------"+loginUser);
            request.setAttribute("userId", loginUser.getUserId());
        }else {
            System.out.println("----------JwtAuthInterceptor token ====null");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 未授权
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"error\":\"Unauthorized\"}");
            System.out.println("------拦截333333333333333333--------");
            return false;
        }
        System.out.println("------------放行44444444444444444-----------------------");
        return true;
    }

}
